package com.pethospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pethospital.entity.Department;
import com.pethospital.entity.Staff;
import com.pethospital.exception.BusinessException;
import com.pethospital.mapper.DepartmentMapper;
import com.pethospital.mapper.StaffMapper;
import com.pethospital.service.DepartmentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Resource
    private StaffMapper staffMapper;

    @Override
    public Page<Department> page(int page, int size) {
        return page(new Page<>(page, size), new LambdaQueryWrapper<Department>()
                .orderByAsc(Department::getId));
    }

    @Override
    public Department getById(Long id) {
        return super.getById(id);
    }

    @Override
    public boolean add(Department department) {
        department.setCreateTime(LocalDateTime.now());
        department.setUpdateTime(LocalDateTime.now());
        return save(department);
    }

    @Override
    public boolean update(Department department) {
        department.setUpdateTime(LocalDateTime.now());
        return updateById(department);
    }

    @Override
    public boolean delete(Long id) {
        // 检查科室是否有关联的医护人员
        Long count = staffMapper.selectCount(new LambdaQueryWrapper<Staff>()
                .eq(Staff::getDepartmentId, id));
        
        if (count > 0) {
            throw new BusinessException("该科室下有关联的医护人员，不能删除");
        }
        
        return removeById(id);
    }
} 